<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <div slot="header" class="clearfix">
          <span>{{ id ? '编辑录入' : '新增录入' }}</span>
        </div>
        <el-form
          ref="ruleForm"
          label-width="80px"
          class="demo-ruleForm"
          :model="formData"
          :rules="rules"
        >
          <!-- 学科 -->
          <el-form-item label="学科:" prop="subjectID">
            <el-select
              v-model="formData.subjectID"
              placeholder="请选择"
              style="width: 40%"
              @change="subjectchange($event)"
            >
              <el-option
                v-for="(item, index) in subjectlist"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item label="目录:" prop="catalogID">
            <el-select
              v-model="formData.catalogID"
              placeholder="请选择"
              style="width: 40%"
            >
              <el-option
                v-for="(item, index) in directorylist"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item label="企业:" prop="enterpriseID">
            <el-select
              v-model="formData.enterpriseID"
              placeholder="请选择"
              style="width: 40%"
            >
              <el-option
                v-for="item in detaillist"
                :key="item.id"
                :label="item.shortName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-row type="flex" justify="center">
            <el-col>
              <el-form-item prop="province" label="城市:" required>
                <el-row type="flex">
                  <!-- 城市 -->
                  <el-col>
                    <el-select
                      v-model="formData.province"
                      placeholder="请选择"
                      value=""
                      @change="Provincechange($event)"
                    >
                      <el-option
                        v-for="(item, index) in citylist1"
                        :key="index"
                        :label="item"
                        :value="item"
                      />
                    </el-select>
                  </el-col>
                  <!-- 地区 -->
                  <el-col>
                    <el-select
                      v-model="formData.city"
                      placeholder="请选择"
                      style=""
                    >
                      <el-option
                        v-for="(item, index) in citylist2"
                        :key="index"
                        :label="item"
                        :value="item"
                      />
                    </el-select>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col />
          </el-row>

          <!-- 方向 -->
          <el-form-item label="方向:" prop="direction">
            <span>
              <el-select
                v-model="formData.direction"
                placeholder="请选择"
                value=""
                style="width: 40%"
              >
                <el-option
                  v-for="item in questionslist"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select> </span></el-form-item>
          <!-- 题型 -->
          <el-form-item label="题型" prop="questionType">
            <el-radio-group
              v-model="formData.questionType"
              @change="clearRight"
            >
              <el-radio
                v-for="questionOption in questionType"
                :key="questionOption.value"
                :label="questionOption.value"
              >{{ questionOption.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item label="难度" prop="difficulty">
            <el-radio-group v-model="formData.difficulty">
              <el-radio
                v-for="difficultyOption in difficulty"
                :key="difficultyOption.value"
                :label="difficultyOption.value"
              >{{ difficultyOption.label }}
              </el-radio></el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item label="题干" prop="question">
            <quill-editor
              ref="myQuillEditor"
              v-model="formData.question"
              class="editor"
              :options="editorOption"
            />
            <!-- <myEditor v-model="formData.question" /> -->
          </el-form-item>
          <!-- 选项 -->
          <el-form-item v-if="formData.questionType * 1 === 1" label="选项:">
            <!--选项-> 单选框 -->
            <el-row
              v-for="(option, index) in formData.options"
              :key="option.code"
            >
              <div style="height: 20px" />
              <el-radio
                v-model="option.isRight"
                :label="option === true ? false : true"
                @change="chooseRight($event, index)"
              >{{ formatCode(option.code) }}:
                <!-- 文本 -->
                <el-input v-model="formData.options[index].title" />
                <!-- 图片
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  multiple
                  :show-file-list="false"
                /> -->
              </el-radio>
            </el-row>
          </el-form-item>
          <el-form-item v-else-if="formData.questionType === 2" label="选项:">
            <!--选项-> 多选框 -->
            <el-row
              v-for="(option, index) in formData.options"
              :key="option.code"
            >
              <div style="height: 20px" />
              <el-checkbox v-model="formData.options[index].isRight">
                {{ formatCode(option.code) }}:
                <!-- 文本 -->
                <el-input v-model="formData.options[index].title" />
                <!-- 图片
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  multiple
                /> -->
              </el-checkbox>
            </el-row>
          </el-form-item>
          <el-form-item
            v-if="formData.questionType == 1 || formData.questionType == 2"
            style="margin: 0 0 0 100px"
          >
            <el-button
              type="danger"
              :disabled="formData.questionType === 1"
              @click="accumulate"
            >增加选项与答案</el-button>
          </el-form-item>
          <!-- 解析视频 -->
          <el-form-item label="解析视频:" style="margin-top: 20px">
            <el-input style="width: 40%" />
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item label="答案解析" prop="answer">
            <quill-editor
              ref="myQuillEditor"
              v-model="formData.answer"
              class="editor"
              :options="editorOption"
            />
            <!-- <myEditor v-model="formData.answer" /> -->
          </el-form-item>
          <!-- 题目备注 -->
          <div class="remarks">
            <el-form-item label="题目备注" prop="remarks">
              <el-input
                v-model="formData.remarks"
                type="textarea"
                rows="6"
                style="width: 30%"
              />
            </el-form-item>
          </div>
          <!-- 试题标签 -->
          <el-form-item label="试题标签:" prop="tags">
            <el-select
              v-model="formData.tags"
              placeholder="请选择试题标签"
              value=""
              style="width: 30%"
              multiple
              :multiple-limit="3"
            >
              <el-option
                v-for="item in tagslist"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <!-- <el-button v-if="formData.id" type="success" @click="submits">确认修改</el-button> -->
            <el-button type="primary" @click="submits">{{ id?'编辑提交' : '确定提交' }}</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// 导入constants
import { questionType, difficulty, direction } from '@/api/hmmm/constants'
// import myEditor from '@/components/myEditor'
// 获取学科目录
import { simple } from '@/api/hmmm/subjects'
// 获取公司目录
import { list } from '@/api/hmmm/companys'
// 获取方向
// import { list as questionslist } from '@/api/hmmm/questions'
// 获取城市列表
import { provinces, citys } from '@/api/hmmm/citys'
// 目录列表
import { simple as directoryssimple } from '@/api/hmmm/directorys'
// 标签列表
import { simple as tagssimple } from '@/api/hmmm/tags'
// 提交表单

import { add, detail, update } from '@/api/hmmm/questions'
import { quillEditor } from 'vue-quill-editor'
import hljs from 'highlight.js'
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],
  [{ list: 'ordered' }, { list: 'bullet' }],
  ['blockquote', 'code-block'],
  ['image', 'link']
]
export default {
  components: {
    // 富文本组件
    quillEditor
  },
  data() {
    // 表单列表
    const validateProvince = (rule, value, callback) => {
      if (value) {
        if (!this.formData.city) {
          callback(new Error('请输入地区'))
        } else {
          callback()
        }
      } else {
        callback(new Error('请输入城市'))
      }
    }
    return {
      id: this.$route.query.id,
      uniqueId: 'uniqueId',
      editorOption: {
        //  富文本编辑器配置
        modules: {
          toolbar: toolbarOptions,
          syntax: {
            highlight: (text) => {
              return hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
            }
          }
        },
        theme: 'snow',
        placeholder: '请输入正文'
      },
      formData: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: 1, // 题型=> 需要转换
        difficulty: 1, // 难度=> 需要转换
        question: '', // 题干
        options: [
          {
            // 选项
            code: '65', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          },
          {
            // 选项
            code: '66', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          },
          {
            // 选项
            code: '67', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          },
          {
            // 选项
            code: '68', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      // 组件选项
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' },
          { required: true, trigger: 'change', validator: validateProvince }
        ],
        city: [{ required: true, message: '请选择区域', trigger: 'change' }],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题目类型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        remarks: [
          { required: true, message: '请输入题目备注', trigger: 'blur' }
        ],
        answer: [{ required: true, message: '请输入题干', trigger: 'blur' }]
      },
      isdisabled: false,
      subjectlist: [], // 学科
      detaillist: {}, // 企业
      questionslist: {}, // 方向
      citylist1: {}, // 城市省
      citylist2: {}, // 城市区
      directorylist: {}, // 目录
      tagslist: {}, // 试题标签
      questionType,
      difficulty
    }
  },
  computed: {
    optionstemp() {
      return this.sortKey(this.formData.options, 'code')
    }
  },
  created() {
    this.simple()
    this.list()
    this.questionslists()
    this.citylist1 = provinces()
    if (this.id) {
      this.basicList()
    }
    // console.log(this.$route.query)
  },
  methods: {
    sortKey(array, key) {
      return array.sort(function(a, b) {
        var x = a[key]
        var y = b[key]
        return x < y ? -1 : x > y ? 1 : 0
      })
    },

    charCodeAt(str) {
      return str.charCodeAt()
    },
    // 获取标签列表
    async tagssimple() {},
    // 点击添加选项
    accumulate() {
      const list = this.formData.options
      const obj = {
        // 选项
        code: `${Number(list[list.length - 1].code) + 1}`, // 代码
        title: '', // 标题
        img: '', // 图片URL
        isRight: '' // 是否正确答案
      }
      this.formData.options.push(obj)
    },

    chooseRight(value, index) {
      if (this.formData.questionType === 1) {
        this.formData.options.forEach((val) => {
          val.isRight = false
        })
        this.formData.options[index].isRight = value
      } else {
        console.log(index)
        this.formData.options[index].isRight = value
      }
    },
    // 学科事件
    async subjectchange(e) {
      this.formData.catalogID = ''
      this.directoryssimple({ subjectID: e })
      const { data } = await tagssimple({ subjectID: e })
      console.log(data)
      this.tagslist = data
      this.formData.subjectID = e
    },
    // 获取目录
    async directoryssimple(ID) {
      const { data } = await directoryssimple(ID)
      this.directorylist = data
      console.log(data)
    },
    // 城市更新方法
    Provincechange(e) {
      this.formData.city = ''
      this.citylist2 = citys(e)
    },
    // 方向
    async questionslists() {
      this.questionslist = direction
      // console.log(this.questionslist)
    },
    // 学科
    async simple() {
      const { data } = await simple()
      this.subjectlist = data
    },
    // 公司
    async list() {
      const {
        data: { items }
      } = await list()
      this.detaillist = items
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    submits() {
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          const list = { ...this.formData }
          list.questionType = `${this.formData.questionType}`
          list.difficulty = `${this.formData.difficulty}`
          list.tags = JSON.stringify(list.tags)
          if (this.id) {
            await update(list)
          } else {
            try {
              // console.log(list)
              const data = await add(list)
              console.log(data)
              this.$message.success('提交成功')
              this.$router.push('list')
              this.$refs.ruleForm.resetFields()
            } catch (err) {
              this.$message.error('网络好像开了小差，请稍后重试')
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    question() {
      console.log(this.$refs.ruleForm)
      this.$refs.ruleForm.validatePass('question')
      this.$refs.ruleForm.validatePass('answeranalysis')
    },
    formatCode(code) {
      return String.fromCharCode(code)
    },
    clearRight() {
      this.formData.options.forEach((v) => {
        v.isRight = false
      })
    },
    // 基础试题详情列表
    async basicList() {
      try {
        const { data } = await detail({ id: this.id })
        data.difficulty = data.difficulty * 1
        data.questionType = data.questionType * 1
        data.options.forEach(item => {
          if (item.isRight === 1) {
            item.isRight = true
          } else {
            item.isRight = false
          }
          item.code = this.charCodeAt(item.code)
        })
        this.formData = data
        console.log(this.formData)
      } catch (err) {
        this.$message.error('未知问题请稍后重试')
      }
    }
  }
}
</script>

<style scoped>
.Options {
  margin-bottom: 20px;
}
.remarks {
  margin-top: 60px !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: absolute;
  top: -5px;
  left: 300px;
  overflow: hidden;
  line-height: 50px;
  width: 100px;
  height: 50px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-icon-circle-close {
  position: absolute;
  top: -9px;
  left: 390px;
  color: #8c939d;
  font-size: 16px;
}
.el-form-item__label {
  width: 90px !important;
}
.el-form-item__content {
  margin-left: 100px !important;
}
.editor {
  height: 200px;
  margin-bottom: 20px;
}
</style>
